package com.hualude.roadsign.controller;

import com.hualude.roadsign.utils.Captcha;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/rds_captcha")
public class CaptchaServlet {

    @RequestMapping("/getCaptcha")
    @ResponseBody
    public void getCaptcha() throws Exception {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        HttpServletRequest request = attributes.getRequest();

        // 设置图片格式
        response.setContentType("image/jpeg");

        // 禁止图像缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);  //在代理服务器端防止缓冲

        Captcha captcha = new Captcha();
        HttpSession rdsUserLoginSession = request.getSession();
        rdsUserLoginSession.setAttribute("imageCode", captcha.getCode());

        /*Cookie cookie = new Cookie("captcha", captcha.getCode());
        cookie.setMaxAge(1800);  //设置cookie有效时间，单位 秒
        response.addCookie(cookie);*/
        captcha.write(response.getOutputStream());

    }
}
